package com.jy.modules.cims.common.controller;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.exception.SysAssistException;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.FileUtils;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.common.service.TCMmImgurlService;
import com.jy.modules.cims.component.common.service.TCMmQuotaRetrunService;
import com.jy.modules.cims.component.image.TransferImagesHelper;
import com.jy.modules.cims.component.sysAssist.ExportAndImport;
import com.jy.modules.cims.data.common.dto.TCMmImgurlDTO;
import com.jy.modules.cims.data.dto.ImgurlDto;
import com.jy.modules.cims.data.dto.PlcImagesDto;
import com.jy.modules.cims.data.dto.credit.CreditImageInformationDto;
import com.jy.modules.platform.sysconfig.service.SysConfigService;
import com.jy.platform.core.common.BaseDTO;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;
    

/**
 * @classname: TCMmImgurlController
 * @description: 定义  该表进件和合同共用此表，若是进件场景，则贷款编号字段存储进件信息主件，合同号存储进件编号 控制层
 * @author:  zhiqiang
 */
@Controller
@Scope("prototype")
@RequestMapping("/tCMmImgurl")
public class TCMmImgurlController extends CimsBaseController{
    private static final Logger logger =  LoggerFactory.getLogger(TCMmImgurlController.class);

    @Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmImgurlService")
    private TCMmImgurlService service;
    
	@Autowired
	@Qualifier("com.jy.modules.platform.sysconfig.service.SysConfigService")
	private SysConfigService sysConfigService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmQuotaRetrunService")
	private TCMmQuotaRetrunService tcmmQuotaRetrunService;
    
	@Autowired
	@Qualifier("com.jy.modules.cims.component.image.TransferImagesHelper")
	private TransferImagesHelper transferImagesHelper;
	
    /**
     * 通过 Controller 请求 跳转 进入至相关 页面
     */
    @RequestMapping(value = "/prepareExecute/{operate}")
    public ModelAndView execute(@PathVariable("operate") String operate) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        
        if("toQueryPage".equals(operate)){//跳转至 查询页面
        	model.setViewName("cims/creditDeal/queryTCMmImgurl");
        }else if("toAdd".equals(operate)){ //跳转至 新增页面
        	model.setViewName("cims/creditDeal/addTCMmImgurl");
        }else if("toUpdate".equals(operate)){//跳转至 修改页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/creditDeal/updateTCMmImgurl");
        }else if("toView".equals(operate)){//跳转至 查看页面
        	String id = this.getParameterString("id");
        	model = this.queryOneDTO(id);
        	model.setViewName("cims/creditDeal/viewTCMmImgurl");
        }
        
        return model;
    }
    
    /**
     * @author zhiqiang
     * @description:查询分页列表
     * @date 2015-01-07 16:22:50
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryListTCMmImgurl")
    @ResponseBody
    public DataMsg queryListTCMmImgurl(HttpServletRequest request, TCMmImgurlDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception {
        
    	Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);
    	
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
        List<TCMmImgurlDTO> list = service.searchTCMmImgurlByPaging(params.getSearchParams());
        
        dataMsg.setData(list);
        dataMsg.setTotalRows(pageInfo.getTotalCount());
        return dataMsg;
    }
    

    /**
     * @author zhiqiang
     * @description:新增
     * @date 2015-01-07 16:22:50
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     * @throws
     */
    @RequestMapping(value = "/insertTCMmImgurl")
    @ResponseBody
    public DataMsg insertTCMmImgurl(HttpServletRequest request, TCMmImgurlDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (TCMmImgurlDTO)super.initDto(dto);

            service.insertTCMmImgurl(dto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("新增成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
        	logger.error("执行方法insertSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * @author zhiqiang
     * @description:编辑
     * @date 2015-01-07 16:22:50
     * @param request
     * @param dto
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/updateTCMmImgurl")
    @ResponseBody
    public DataMsg updateTCMmImgurl(HttpServletRequest request, TCMmImgurlDTO dto, @ModelAttribute DataMsg dataMsg){
        try {
        	dto = (TCMmImgurlDTO)super.initDto(dto);
           
            service.updateTCMmImgurl(dto);
            
            dataMsg = super.initDataMsg(dataMsg);
            dataMsg.setMsg("修改成功");
            dataMsg.setData(this.makeJSONData(dto.getId()));
        }catch (Exception e) {
        	dataMsg.failed(e.getMessage());
            logger.error("执行方法updateSysResource异常：", e);
        }
        return dataMsg;
    }

    /**
     * @author zhiqiang
     * @description:删除
     * @date 2015-01-07 16:22:50
     * @param request
     * @param pageData
     * @return
     * @throws
     */
    @RequestMapping(value = "/deleteTCMmImgurl")
    @ResponseBody
    public DataMsg deleteTCMmImgurl(HttpServletRequest request, @ModelAttribute DataMsg dataMsg){
    	
    	BaseDTO dto = super.initDto(null);
   	 	String ids = (String) this.getParameter("ids");//格式: 1,2,3
   	 	dataMsg = super.initDataMsg(dataMsg);
		try {
			 service.deleteTCMmImgurlByPrimaryKey(dto,ids);
			 dataMsg.setMsg("删除成功");
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			logger.error("执行方法deleteSysResource异常：", e);

		}
        
        return dataMsg;
    }
    /**
     * @author zhiqiang
     * @description:通过主键查询 其明细信息
     * @date 2015-01-07 16:22:50
     * @param id
     * @return
     */
    private ModelAndView queryOneDTO(String id) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        try{
        	TCMmImgurlDTO dto = service.queryTCMmImgurlByPrimaryKey(id);
            //将信息放入 model 以便于传至页面 使用
            model.addObject("dto", dto);
        }catch(Exception e){
        	throw new AbaboonException("执行queryOneDTO异常：",e);
        }
        return model;
    }
    
    /**
     * 导出影响文件列表
     * @param request
     * @param dto
     * @param dataMsg
     * @return
     */
    @RequestMapping(value = "/exportImgurl")
	@ResponseBody
    public void exportCooperorgFormTotalByDay(HttpServletRequest request,HttpServletResponse response, ImgurlDto dto, @ModelAttribute DataMsg dataMsg){
    	
		String contractNo = this.getParameterString("contractNo");
		List<String> contractNolist=new ArrayList<String>();
        StringTokenizer st=new StringTokenizer(contractNo,",");
        while(st.hasMoreTokens()){
        	contractNolist.add("'" + st.nextToken() + "'");
        }
  
		String fileName = "影像文件列表";
    	dto.setContractNoList(contractNolist);
    	Map<String, Object> searchParams = new HashMap<String, Object>();
		searchParams.put("dto", dto);
		
		
    	ExportAndImport<TCMmImgurlDTO> exportAndImport = new ExportAndImport<TCMmImgurlDTO>();
    	String columnCode = CimsConstant.IMGURL_FILE_EXPORT_CODE;
    	String columnName = CimsConstant.IMGURL_FILE_EXPORT_NAME;
		HSSFWorkbook workbook;
		try {
			List<TCMmImgurlDTO> list = service.searchTCMmImgurl(searchParams);
			workbook = exportAndImport.exportExcelSubsidiary(fileName, columnCode, columnName, list);
			write(workbook, fileName, response);
		} catch (Exception e) {
			e.printStackTrace();
			dataMsg.failed(e.getMessage());
			throw new SysAssistException(CimsExceptionConstant.INGURL_FILE + e);
		}
    }
    
    /**
     * 下载影像文件
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("/exportImgUrlZip")
    @ResponseBody
	public void exportImgUrlZip(HttpServletRequest request, HttpServletResponse response, ImgurlDto dto, @ModelAttribute DataMsg dataMsg) throws Exception {
    	
    	Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHms");
    	String dateTimeString = format.format(c.getTime());
    	String contractNo = this.getParameterString("contractNo");
    	String cooperorgCode = this.getParameterString("cooperorgCode");
    	String filePath = sysConfigService.queryValueByCode("org.tmp.file.path")+"/localDownZipTemp";
		transferImagesHelper.createTempDir(filePath);
    	response.setContentType("application/x-download charset=UTF-8");
		List<String> contractNolist=new ArrayList<String>();
        StringTokenizer st=new StringTokenizer(contractNo,",");
        while(st.hasMoreTokens()){
        	contractNolist.add("'" + st.nextToken() + "'");
        }
        ZipOutputStream zos = null;
        ServletOutputStream servletOutputStream = null;
        
        /**
         * 
         * 过滤条件
         * */
        PlcImagesDto searchDto = new PlcImagesDto();
        searchDto.setCooperorgCode(cooperorgCode);
        String attachNames = null;
        if(SimpleStringUtils.hasText(cooperorgCode)){
			List<CreditImageInformationDto> listAttacs = tcmmQuotaRetrunService.queryDataToWn(searchDto);
			if(CollectionsUtils.isNotEmpty(listAttacs)&&listAttacs.get(0)!=null){
				attachNames = listAttacs.get(0).getDictDetailValue();
				attachNames = "'"+attachNames.replace(",", "','")+"'";
			}
        }
        
		try {
			
			//开始下载文件
			for(int m=0;m<contractNolist.size();m++){
				List<String> listCode=new ArrayList<String>();
				listCode.add(contractNolist.get(m));
				dto.setContractNoList(listCode);
				dto.setAttachNames(attachNames);
		    	Map<String, Object> searchParams = new HashMap<String, Object>();
				searchParams.put("dto", dto);
				List<TCMmImgurlDTO> list = service.searchTCMmImgurl(searchParams);
				String contractCode = contractNolist.get(m).replace("'", "");
				String fileOutUrl = filePath + "/" + dateTimeString + "/" + contractCode + "/";	
				File file=new File(fileOutUrl);
				if(!file.exists()){
		    		file.mkdirs();
		    	}
				//创建目录
				transferImagesHelper.createTempDir(fileOutUrl);
				for(int i=0;i<list.size();i++){
					TCMmImgurlDTO tCMmImgurlDTO = list.get(i); 
					String fileUrl = tCMmImgurlDTO.getAttachUrl();
					String fileName = FilenameUtils.getName(fileUrl);
					if("FZDY".equalsIgnoreCase(cooperorgCode) || "QKDK".equalsIgnoreCase(cooperorgCode)){
						fileName = tCMmImgurlDTO.getAttachName();
					}
					String fileOutUrlName = fileOutUrl + fileName;
					this.createImage(fileUrl,fileOutUrlName);
				}
				list = null;
				file = null;
			}
			response.setHeader("Content-disposition", "attachment;filename=" + dateTimeString + ".zip");
	    	servletOutputStream = response.getOutputStream();
			String zipFileOutUrl = filePath + "/" + dateTimeString + "/";
			zos = new ZipOutputStream(servletOutputStream);
		    
		    //开始打包
            this.writeZip(new File(zipFileOutUrl), "", zos);
            
		} catch (Exception e) {
			dataMsg.failed(e.getMessage());
			throw new SysAssistException(CimsExceptionConstant.DOWN_LOAD_FILE + e.getMessage());
		}finally{
			if(zos!=null){
				zos.close();
			}
			if(servletOutputStream!=null){
				servletOutputStream.close();
			}
			FileUtils.deleteDirectory(filePath);
		}
		
	}
    
    /**
     * @param urlAdd （url地址）
	 * @param fileName（生成文件的名称）
	 */

	private void createImage(String imgurl, String filePath) throws Exception {

		URL url = new URL(imgurl);

		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		InputStream inputStream = conn.getInputStream(); // 通过输入流获得图片数据
		byte[] getData = readInputStream(inputStream); // 获得图片的二进制数据

		File imageFile = new File(filePath);
		FileOutputStream fos = new FileOutputStream(imageFile);
		fos.write(getData);
		fos.close();
	}
	
	/**
	 * 输入流
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	private  byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while ((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}
	
	/**
	 * 压缩文件
	 * @param file
	 * @param parentPath
	 * @param zos
	 */
    private void writeZip(File file, String parentPath, ZipOutputStream zos) {
        if(file.exists()){
            if(file.isDirectory()){//处理文件夹
                parentPath+=file.getName()+File.separator;
                File [] files=file.listFiles();
                if(null != files){
                for(File f:files){
                    writeZip(f, parentPath, zos);
                }
                }
            }else{
                FileInputStream fis=null;
                DataInputStream dis=null;
                try {
                    fis=new FileInputStream(file);
                    dis=new DataInputStream(new BufferedInputStream(fis));
                    ZipEntry ze = new ZipEntry(parentPath + file.getName());
                    zos.putNextEntry(ze);
                    byte [] content=new byte[1024];
                    int len;
                    while((len=fis.read(content))!=-1){
                        zos.write(content,0,len);
                        zos.flush();
                    }
                    
                
                } catch (Exception e) {
                	logger.error("创建ZIP文件失败",e);
                }finally{
                    try {
                        if(dis!=null){
                            dis.close();
                        }
                    }catch(IOException e){
                    	logger.error("创建ZIP文件失败",e);
                    }
                }
            }
        }
    }
    
    /**
	 * 页面输出
	 * 
	 * @param workbook
	 * @param fileName
	 * @param response
	 * @throws IOException
	 */
	private void write(HSSFWorkbook workbook, String fileName, HttpServletResponse response) throws IOException {

		try {
			
			response.setContentType("application/vnd.ms-excel");
			response.setContentType("application/vnd.openxmlformatSs-officedocument.spreadsheetml.sheet");
			response.setCharacterEncoding("UTF-8");
			response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xls");
			workbook.write(response.getOutputStream());
			response.getOutputStream().flush();
		} catch (Exception e) {
			throw new SysAssistException(CimsExceptionConstant.EXPORT_EXCEL_FAIL + e.getMessage());
		} finally {
			response.getOutputStream().close();
		}
	}
}
